#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @FileName  :下载m3u8音频测试.py
# @Time      :2024/3/21 
# @Author    :CL
# @email     :1037654919@qq.com
import shutil

import requests
import os
import subprocess

# 下载.m3u8链接中的音频文件
def download_m3u8_audio(m3u8_url):
    # 下载.m3u8文件内容
    response = requests.get(m3u8_url)
    m3u8_content = response.text

    # 匹配所有的.ts文件链接并添加正确的schema
    base_url = '/'.join(m3u8_url.split('/')[:-1]) + '/'

    ts_urls = [base_url + line.strip() for line in m3u8_content.split('\n') if line.endswith('.ts')]
    print(ts_urls)
    # 创建保存音频文件的文件夹
    folder_name = 'audio_files'
    if not os.path.exists(folder_name):
        os.makedirs(folder_name)

    # 下载每个.ts文件
    for index, ts_url in enumerate(ts_urls, start=1):
        response = requests.get(ts_url)
        file_path = os.path.join(folder_name, f"audio_{index}.ts")
        with open(file_path, 'wb') as f:
            f.write(response.content)

    print("音频文件下载完成")
# 合并所有的.ts文件为单个音频文件
def merge_ts_files(input_folder, output_file):
    ts_files = [f for f in os.listdir(input_folder) if f.endswith('.ts')]
    file_list_path = os.path.join(input_folder, 'file_list.txt')

    # 将.ts文件列表写入文件
    with open(file_list_path, 'w') as f:
        for ts_file in ts_files:
            f.write(f"file '{ts_file}'\n")

    # 使用ffmpeg合并.ts文件为单个音频文件
    subprocess.run(['ffmpeg', '-f', 'concat', '-safe', '0', '-i', file_list_path, '-c copy' '-bsf:a aac_adtstoasc','-y', output_file])

    # 删除中间文件
    os.remove(file_list_path)

    # 删除保存.ts文件的文件夹
    shutil.rmtree(input_folder)

# 使用示例
m3u8_url = 'https://mediastorage.cnr.cn/record/audio/cnr/CNRCDP/2024/0316/ed40660ffde681710604661532752769/ed40660ffde681710604661532752769.m3u8?auth=ae3b1920bc1c041125f8ea14265f1a00'
# download_m3u8_audio(m3u8_url)

input_folder = 'audio_files'
output_file = 'output.m3u8'
merge_ts_files(input_folder, output_file)



